package com.jdk.learn.thread;

/**
 * 每个线程独享自己内部变量
 * <p>
 * 即为每个线程提供一个局部变量
 * 底层是使用线程对象进行map值匹配
 */
public class ThreadLocalDemo extends Thread {
    private UUIDNumEach num;

    public ThreadLocalDemo(UUIDNumEach num) {
        this.num = num;
    }

    @Override
    public void run() {
        for (int i = 0; i < 4; i++) {
            System.out.println("name:" + getName() + ",uuidnum:" + num.getNum());
        }
    }

    public static void main(String[] args) {
        UUIDNumEach num = new UUIDNumEach();
        ThreadLocalDemo t1 = new ThreadLocalDemo(num);
        ThreadLocalDemo t2 = new ThreadLocalDemo(num);
        ThreadLocalDemo t3 = new ThreadLocalDemo(num);
        t1.start();
        t2.start();
        t3.start();
    }
}

class UUIDNumEach {
    public static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };//默认是0
    public int count = 0;

    public int getNum() {
        int i = threadLocal.get() + 1;
        threadLocal.set(i);
        return i;
    }
}